package com.xsmart.common.services;

import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.EcomException;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.common.entity.ApiInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

@Service
public class ApiCallService {
    @Autowired
    private RestTemplate loadBalanced;
    @Autowired
    private GetApiInfoService getApiInfoService;

    public Object call(String version, String serviceName, String methodName, RequestBean requestBean, HttpServletRequest request) throws EcomException {
        String methodUri = "/api/" + version + "/" + serviceName + "/" + methodName;
        ApiInfo apiInfo = getApiInfoService.getApiInfo(methodUri);
//        if(apiInfo.getServiceId()==-1){
//            throw new EcomException(ResultConstant.ERROR,"服务不存在",new Throwable());
//        }
        HttpHeaders headers = new HttpHeaders();
        if (request != null) {
            headers.setAccept(Collections.singletonList(MediaType.parseMediaType(request.getContentType())));
            headers.add("call_remote_host", request.getRemoteAddr());
        }
        HttpEntity<RequestBean> entity = new HttpEntity<>(
                requestBean, headers);
        ResponseEntity<String> responseEntity = loadBalanced.exchange(apiInfo.getUrl(), HttpMethod.POST, entity, new ParameterizedTypeReference<String>() {
        });
        return responseEntity.getBody();
    }
}
